package com.tran.app

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import androidx.room.util.query
import com.orhanobut.logger.Logger
import com.tran.app.dao.AppDatabase
import com.tran.app.data.Teacher
import com.tran.app.repository.DataStoreManager
import com.tran.app.screen.CSScreen
import com.tran.app.screen.CourseScreen
import com.tran.app.screen.CreatePlain
import com.tran.app.screen.DropCourseScreen
import com.tran.app.screen.DropScreen
import com.tran.app.screen.Login
import com.tran.app.screen.Main
import com.tran.app.screen.MainTeach
import com.tran.app.screen.PublicSreen
import com.tran.app.screen.Register
import com.tran.app.screen.ScopeUpdateScope
import com.tran.app.screen.ShowCourseScreen
import com.tran.app.screen.UpdateUserInfo
import com.tran.app.ui.theme.AppTheme
import com.tran.app.viewmodel.LoginViewModel
import com.tran.app.viewmodel.PlainViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext

class MainActivity : ComponentActivity() {

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            AppTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    val navCotroller = rememberNavController()
                    NavHost(navController = navCotroller, startDestination ="welcome" ) {
                        composable("welcome"){
                            Welcome(Modifier.padding(innerPadding),navCotroller)
                        }
                        composable("update/{cid}", arguments = listOf(
                            navArgument("cid"){
                                type = NavType.IntType
                            }
                        )){
                            val id = it.arguments?.getInt("cid")
                            ScopeUpdateScope(Modifier.padding(innerPadding),navCotroller, id!!)
                        }
                        composable("show?query={query}", arguments = listOf(
                            navArgument("query"){
                                type = NavType.StringType
                                nullable = true
                            }
                        )){
                            val type = it.arguments?.getString("query")
                            ShowCourseScreen(Modifier.padding(innerPadding),navCotroller,
                                type.toString()
                            )
                        }
                        composable("course/{cid}", arguments = listOf(
                            navArgument("cid"){
                                type = NavType.IntType
                            }
                        )){
                            val id = it.arguments?.getInt("cid")
                            CourseScreen(Modifier.padding(innerPadding),navCotroller,id!!)
                        }
                        composable("drop"){
                            DropScreen(Modifier.padding(innerPadding),navCotroller)
                        }
                        composable("login"){
                            val vm = LoginViewModel()
                            Login(Modifier.padding(innerPadding),navController = navCotroller,vm)
                        }
                        composable("register"){
                            Register(Modifier.padding(),navController = navCotroller)
                        }
                        composable("dropCourse"){
                            DropCourseScreen(Modifier.padding(),navCotroller = navCotroller)
                        }
                        composable("UpdateUserInfo"){
                            UpdateUserInfo(Modifier.padding(),navController = navCotroller)
                        }
                        composable("CSS"){
                            CSScreen(Modifier.padding(),navCotroller = navCotroller)
                        }
                        composable("maintech"){
                            MainTeach(Modifier.padding(innerPadding),navController = navCotroller)
                        }
                        composable("public"){
                            PublicSreen(Modifier.padding(),navController = navCotroller)
                        }
                        composable("main/{name}", arguments = listOf(
                            navArgument("name"){
                                type = NavType.StringType
                            }
                        )){
                            Main(Modifier.padding(innerPadding),navController = navCotroller)
                        }
                        composable("createplain?id={id}",
                            arguments = listOf(
                                navArgument("id"){
                                    type = NavType.IntType
                                    defaultValue = -1
                                    nullable = false
                                }
                            )
                            ){
                            val id = it.arguments?.getInt("id") ?:0
                            val vm = PlainViewModel()
                            CreatePlain(Modifier.padding(),navController = navCotroller,vm,id)
                        }
                    }
                }
            }
        }
    }
}

private val dataStore = DataStoreManager(MyApp.instance)

@Composable
fun Welcome(modifier: Modifier,navController: NavController) {
    val scape = rememberCoroutineScope()
    val context = LocalContext.current
    LaunchedEffect(key1 = Unit) {
        withContext(Dispatchers.IO) {
            var isload = false
            Logger.d("usload==="+isload)
            dataStore.getTeachSp().first().also {
                isload = it
            }
            Logger.d("usload==="+isload)
            if(!isload){
                insertTeachers()
                dataStore.setTeachSp()
            }
        }
        delay(2000)
        withContext(Dispatchers.Main){
            navController.navigate("login")
            navController.popBackStack()
        }
    }
 Box(modifier =modifier.fillMaxSize()) {
     Text(
         text = "欢迎",
         modifier =Modifier.align(Alignment.Center)
     )
 }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    AppTheme {
        Greeting("Android")
    }
}


private suspend fun insertTeachers() {
    // 生成几组教师数据
    val teachers = listOf(
        Teacher("001", "张老师", ("zhang_password123")),
        Teacher("002", "李老师", ("li_password456")),
        Teacher("003", "王老师", ("003")),
        Teacher("123", "白老师", "123"),
    )

    withContext(Dispatchers.IO) { // 确保在 IO 调度器上执行数据库操作
        teachers.forEach {
            AppDatabase.getInstance(MyApp.instance).teacherDao().insertTeacher(it)
        }

    }
}
